const fileService = require('../service/file.service')
const userService = require('../service/user.service')
const R = require('../utils/R')
const { server } = require('../env')
const { UPLOAD_AVATAR_EXCEPTION } = require('../error/errorType')
const { ossUploadHandler } = require('../utils/upload')

const { host, port } = server

class FileController {
    // 头像上传
    async uploadAvatar(ctx, next) {
        try {
            const { avatar, isLocal, userInfo } = ctx
            const { id: userId } = userInfo
            if (isLocal) {
                const { filename, mimetype, size } = avatar
                let result = await fileService.insertAvatar(filename, mimetype, size, userId)
                if (result.insertId) {
                    let avatarUrl = `http://${host}:${port}/static/${filename}`
                    // 更新user表
                    await userService.updateAvatar(avatarUrl, userId)
                    ctx.dto = R.ok('上传头像成功', { url: avatarUrl })
                } else {
                    ctx.dto = R.error(UPLOAD_AVATAR_EXCEPTION, null)
                }
            } else {
                let avatarUrl = await ossUploadHandler('avatar', avatar)
                if (avatarUrl) {
                    // 更新user表
                    await userService.updateAvatar(avatarUrl, userId)
                    ctx.dto = R.ok('上传头像成功', { url: avatarUrl })
                } else {
                    ctx.dto = R.error(UPLOAD_AVATAR_EXCEPTION, null)
                }
            }


        } catch (err) {
            console.log(err.message)
            return ctx.app.emit('error', new Error(UPLOAD_AVATAR_EXCEPTION), ctx)
        }
        await next()
    }
}

module.exports = new FileController()